<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    @ok="handleSubmit"
    @cancel="close"
    style="top:50px"
    cancelText="关闭">

    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="编号">
                <a-input placeholder="请输入编号" v-model="queryParam.code"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="名称">
                <a-input placeholder="请输入名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <template v-if="toggleSearchStatus">
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label="状态">
                  <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="erp_status"/>
                </a-form-item>
              </a-col>
            </template>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->

      <!-- table区域-begin -->
      <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div>

        <a-table
          ref="table"
          size="middle"
          rowKey="id"
          class="j-table-force-nowrap"
          :scroll="{x:true}"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :expandedRowKeys="expandedRowKeys"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
          @change="handleTableChange"
          @expand="handleExpand"
          v-bind="tableProps">
        </a-table>
      </div>
    </a-card>

  </j-modal>
</template>

<script>

import {getAction} from '@/api/manage'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {filterObj} from '@/utils/util';

export default {
  name: "JSelectGoodsCategoryListModal",
  mixins: [JeecgListMixin],
  components: {},
  props: ['modalWidth', 'multi', 'text'],
  data() {
    return {
      description: 'erp_goods_category管理页面',
      queryParam: {},
      selectedRowKeys: [],
      visible: false,
      title: '选择物料种类',
      // 表头
      columns: [
        {
          title: '名称',
          align: "left",
          dataIndex: 'name'
        },
        {
          title: '编号',
          align: "left",
          dataIndex: 'code'
        }
      ],
      url: {
        list: "/goods/erpGoodsCategory/rootList",
        childList: "/goods/erpGoodsCategory/childList",
        getChildListBatch: "/goods/erpGoodsCategory/getChildListBatch",
        delete: "/goods/erpGoodsCategory/delete",
        deleteBatch: "/goods/erpGoodsCategory/deleteBatch",
        exportXlsUrl: "/goods/erpGoodsCategory/exportXls",
        importExcelUrl: "goods/erpGoodsCategory/importExcel",
      },
      expandedRowKeys: [],
      hasChildrenField: "hasChild",
      pidField: "parentId",
      dictOptions: {},
      loadParent: false,
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList();
  },
  computed: {
    getType: function () {
      return 'radio';
    },
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => _this.selectedRowKeys = selectedRowKeys
        }
      }
    }
  },
  methods: {
    showModal() {
      this.visible = true;
      this.loadData();
    },
    close() {
      this.searchReset(0);
      this.visible = false;
    },
    handleSubmit() {
      let that = this;
      this.getSelectRows();
      that.searchReset(0)
      that.close();
    },
    getSelectRows() {
      let selectedRow = {};
      for (let row of this.selectionRows) {
        if (this.selectedRowKeys.includes(row.id)) {
          selectedRow = row;
        }
      }
      this.$emit('categoryOk', selectedRow);
    },
    loadData(arg) {
      if (arg == 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let params = this.getQueryParams()
      params.hasQuery = 'true'
      getAction(this.url.list, params).then(res => {
        if (res.success) {
          let result = res.result
          if (Number(result.total) > 0) {
            this.ipagination.total = Number(result.total)
            this.dataSource = this.getDataByResult(res.result.records)
            return this.loadDataByExpandedRows(this.dataSource)
          } else {
            this.ipagination.total = 0
            this.dataSource = []
          }
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
    loadDataByExpandedRows(dataList) {
      if (this.expandedRowKeys.length > 0) {
        return getAction(this.url.getChildListBatch, {parentIds: this.expandedRowKeys.join(',')}).then(res => {
          if (res.success && res.result.records.length > 0) {
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map();
            for (let item of records) {
              let pid = item[this.pidField];
              if (this.expandedRowKeys.join(',').includes(pid)) {
                let mapList = listMap.get(pid);
                if (mapList == null) {
                  mapList = [];
                }
                mapList.push(item);
                listMap.set(pid, mapList);
              }
            }
            let childrenMap = listMap;
            let fn = (list) => {
              if (list) {
                list.forEach(data => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = this.getDataByResult(childrenMap.get(data.id))
                    fn(data.children)
                  }
                })
              }
            }
            fn(dataList)
          }
        })
      } else {
        return Promise.resolve()
      }
    },
    getQueryParams(arg) {
      //获取查询条件
      let sqp = {}
      let param = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      if (arg) {
        param = Object.assign(sqp, this.isorter, this.filters);
      } else {
        param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);
      }
      if (JSON.stringify(this.queryParam) === "{}" || arg) {
        param.hasQuery = 'false'
      } else {
        param.hasQuery = 'true'
      }
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return filterObj(param);
    },
    searchReset() {
      //重置
      this.expandedRowKeys = []
      this.queryParam = {}
      this.loadData(1);
    },
    getDataByResult(result) {
      if (result) {
        return result.map(item => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = {id: item.id + '_loadChild', name: 'loading...', isLoading: true}
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        if (record.children.length > 0 && record.children[0].isLoading === true) {
          let params = this.getQueryParams(1);//查询条件
          params[this.pidField] = record.id
          params.hasQuery = 'false'
          params.superQueryParams = ""
          getAction(this.url.childList, params).then((res) => {
            if (res.success) {
              if (res.result.records) {
                record.children = this.getDataByResult(res.result.records)
                this.dataSource = [...this.dataSource]
              } else {
                record.children = ''
                record.hasChildrenField = '0'
              }
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      } else {
        let keyIndex = this.expandedRowKeys.indexOf(record.id)
        if (keyIndex >= 0) {
          this.expandedRowKeys.splice(keyIndex, 1);
        }
      }
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({type: 'string', value: 'code', text: '编号', dictCode: ''})
      fieldList.push({type: 'string', value: 'name', text: '名称', dictCode: ''})
      fieldList.push({type: 'string', value: 'parentId', text: '父级ID', dictCode: ''})
      fieldList.push({type: 'int', value: 'status', text: '状态', dictCode: 'erp_status'})
      fieldList.push({type: 'string', value: 'remark', text: '备注', dictCode: ''})
      fieldList.push({type: 'string', value: 'pid', text: '父级节点', dictCode: ''})
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>